package http_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"gitee.com/zhoulvvv/my_go_gateway/services"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"log"
	"strings"
)

// token 校验中间件
func HTTPJwtOAuthTokenModeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 判断是否开启了权限校验
		if service.AccessControl.OpenAuth == 1 {
			// 0、从请求头中获取token信息
			// Bearer token
			token := strings.ReplaceAll(c.GetHeader("Authorization"), "Bearer ", "")
			log.Printf("token校验中间件：%s\n", token)
			if token == "" {
				middleware.ResponseError(c, 6001, errors.New("没有权限访问该接口"))
				c.Abort()
				return
			}
			// 1、解密token
			claims, err := public.JwtDecode(token)
			log.Printf("token解密信息：%s\n", public.ObjToJson(claims))
			if err != nil {
				middleware.ResponseError(c, 6001, errors.New("校验token中间件中解析token失败："+err.Error()))
				c.Abort()
				return
			}
			// 2、获取到app_id，在根据app_id得到app信息
			appId := claims.Issuer
			appList := services.AppManagerHandler.GetAppList()
			appFlag := false
			for _, item := range appList {
				if item.AppId == appId {
					// 3、把app信息放入到gin的上下文中
					c.Set("app", item)
					appFlag = true
					break
				}
			}
			if !appFlag {
				middleware.ResponseError(c, 6001, errors.New("没有匹配到对应的用户信息"))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
